
//
//  RecentChatManager.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/24.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "RecentChatManager.h"
#import "DBHelper.h"
#import "RecentChatConfig.h"


@implementation RecentChatManager

+ (RecentChatManager*)sharedInstance {
    static dispatch_once_t onceBasicToken;
    
    static RecentChatManager *rcManager = nil;
    
    dispatch_once(&onceBasicToken, ^{
        rcManager = [[RecentChatManager alloc] init];
    });
    return rcManager;
}

- (id)init {
    if (self = [super init]) {
        [self createRecentChatTable]; 
    }
    return self;
}

#pragma mark - -------最近聊天表操作相关--------
- (BOOL)createRecentChatTable {
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar)", TABLE_RECENTCHAT, RC_friendid,RC_friendLogo,RC_friendName,RC_newerMsg,RC_displayMsg,RC_unreadCount,RC_updateTime,RC_msgSourceType,RC_msgBodyType,RC_msgState];
    __block BOOL suc = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue.database executeStatements:sql];
    return suc;
}

/**
 @brief 插入或新增聊天记录（用于接收到新消息或发送消息）
 @param recentData 要插入或修改的RecentConcactData对象
 @return 数据库操作是否成功
 */
- (BOOL)insertOrUpdateRecentWithData:(RecentChat *)recentData
{
    // 查询时候已经在最近聊天消息列表中存在
    BOOL isExistRecentData = [self isExistRecentDataWithFriendid:recentData.friendid];
    
    BOOL bol = NO;
    if (isExistRecentData) {
        // 如果存在，更新消息列表
        bol = [self updateRecentData:recentData];
    }else{
        // 不存在，作为新消息插入到消息列表
        bol = [self insertRecentData:recentData];
    }
    return bol;
}

/**
 @brief 插入数据
 @param recentData 要插入或修改的RecentConcactData对象
 @return 数据库操作是否成功
 */
- (BOOL)insertRecentData:(RecentChat *)recentData
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (%@, %@, %@, %@, %@, %@, %@, %@,%@,%@) VALUES (?,?,?,?,?,?,?,?,?,?)",TABLE_RECENTCHAT,RC_friendid,RC_friendLogo,RC_friendName,RC_newerMsg,RC_displayMsg,RC_unreadCount,RC_updateTime,RC_msgSourceType,RC_msgBodyType,RC_msgState];
    
    NSArray *params = @[objectToString(recentData.friendid),
                        objectToString(recentData.friendLogo),
                        objectToString(recentData.friendName),
                        objectToString(recentData.newerMsg),
                        objectToString(recentData.displayMsg),
                        intToString(recentData.unreadCount),
                        objectToString(recentData.updateTime),
                        intToString(recentData.msgSourceType),
                        intToString(recentData.msgBodyType),
                        intToString(recentData.msgState)];
    BOOL bol = [(FMDatabase *)[dbQueue database] executeUpdate:sql withArgumentsInArray:params];

    return bol;
}

/**
 @brief 更新数据
 @param recentData 要插入或修改的RecentConcactData对象
 @return 数据库操作是否成功
 */
- (BOOL)updateRecentData:(RecentChat *)recentData
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=?, %@=?, %@=?, %@=?, %@=?, %@=?, %@=?, %@=?, %@=?, %@=? WHERE %@=?", TABLE_RECENTCHAT,RC_friendid,RC_friendLogo,RC_friendName,RC_newerMsg,RC_displayMsg,RC_unreadCount,RC_updateTime,RC_msgSourceType,RC_msgBodyType,RC_msgState,RC_friendid];
    
    NSArray *params = @[objectToString(recentData.friendid),
                        objectToString(recentData.friendLogo),
                        objectToString(recentData.friendName),
                        objectToString(recentData.newerMsg),
                        objectToString(recentData.displayMsg),
                        intToString(recentData.unreadCount),
                        objectToString(recentData.updateTime),
                        intToString(recentData.msgSourceType),
                        intToString(recentData.msgBodyType),
                        intToString(recentData.msgState)];
    BOOL bol = [(FMDatabase *)[dbQueue database] executeUpdate:sql withArgumentsInArray:params];

    return bol;
}

/**
 @brief 更新近期聊天人员的基本信息
 @param information 更新内容
 @param uType 更新类型
 @return 数据库操作是否成功
 */
- (BOOL)updateRecentChatTableWithInfo:(id)information updateType:(kRecentChatInfoStyle)uType friendid:(NSString *)Friendid
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *sql;
    NSArray *args;
    switch (uType) {
        case kRecentChatInfoStylemsgState:
        {
            sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=? WHERE %@=?", TABLE_RECENTCHAT, RC_msgState, RC_friendid];
            args = [NSArray arrayWithObjects:(NSNumber *)information,Friendid,nil];
        }
            break;
            
        case kRecentChatInfoStylemsgLogo:
        {
            sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=? WHERE %@=?", TABLE_RECENTCHAT, RC_friendLogo, RC_friendid];
            args = [NSArray arrayWithObjects:(NSString *)information,Friendid,nil];
        }
            break;
            
        default:
            break;
    }
    
    BOOL suc  = [dbQueue.database executeQuery:sql withArgumentsInArray:args];
    return suc;
}

/**
 @brief 队列中更新近期聊天人员的基本信息
 @param information 更新内容
 @param uType 更新类型
 @return 数据库操作是否成功
 */
- (BOOL)updateRecentChatTableWithInfoAtQueue:(id)information updateType:(kRecentChatInfoStyle)uType friendid:(NSString *)Friendid {
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
     __block BOOL suc = NO;
    [dbQueue inDatabase:^(FMDatabase *db) {
      suc =  [self updateRecentChatTableWithInfo:information updateType:uType friendid:Friendid];
    }];
    return suc;
}

/**
 @brief  根据客户ID查询最近聊天消息
 @param  friendid  导购ID
 @return 指定最近聊天人员最新的聊天信息
 */
- (RecentChat *)selectRecentDataWithFriendid:(NSString *)friendid
{
    __block RecentChat *recentChat = nil;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ = %@",TABLE_RECENTCHAT,RC_friendid,friendid];
    
    FMResultSet *rs = [dbQueue.database executeQuery:sql];
    
    if ([rs next]) {
        recentChat = [RecentChat recentConcactDataFromDB:rs];
    }
    [rs close];
  
    return recentChat;
}

/**
 @brief   队列中根据客户ID查询最近聊天消息
 @param  storeId  导购ID
 @return  指定最近聊天人员最新的聊天信息
 */
- (RecentChat *)selectRecentDataAtQueueWithFriendid:(NSString *)friendid
{
    __block RecentChat *recentChat = nil;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        recentChat = [self selectRecentDataWithFriendid:(NSString *)friendid];
    }];
    
    return recentChat;
}


/**
 @brief  查询并删除某个客户的最近聊天记录
 @param  friendid  导购ID
 */
- (void)selectAndDeleteRecentDataWithFriendid:(NSString *)friendid
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        BOOL bol = [self isExistRecentDataWithFriendid:friendid];
        if (bol) {
            [self deleteRecentContactTableWithFriendid:friendid];
        }
    }];
}

/**
 @brief  删除某个客户的最近聊天记录
 @return 是否删除成功
 */
- (BOOL)deleteRecentContactTableWithFriendid:(NSString *)friendid
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=%@", TABLE_RECENTCHAT, RC_friendid, friendid];
    BOOL bol = [(FMDatabase *)[dbQueue database] executeUpdate:sql];
    return bol;
}

/**
 @brief  判断对应消息在最近消息列表中是否存在
 @param  friendid  导购ID
 @return 是否存在记录
 */
- (BOOL)isExistRecentDataWithFriendid:(NSString *)friendid
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=%@ order by %@ desc",TABLE_RECENTCHAT, RC_friendid, friendid,RC_updateTime];
    
    FMResultSet *result = [(FMDatabase *)[dbQueue database] executeQuery:sql];
    
    while ([result next]) {
        RecentChat *data = [RecentChat recentConcactDataFromDB:result];
        [tempArr addObject:data];
    }
    
    if (tempArr.count > 0) {
        return YES;
    }
    return NO;
}

/**
 @brief  队列中判断对应消息在最近消息列表中是否存在
 @param  storeId  导购ID
 @return 是否存在记录
 */
- (BOOL)isExistRecentDataWithStoreIdAtQueue:(NSString *)storeId
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        bol = [self isExistRecentDataWithFriendid:storeId];
    }];
    
    return bol;
}


/**
 @brief  创建公共账号信息
 @return 公共账号数据
 */
- (NSMutableDictionary *)createPublicAccountInfo
{
    NSMutableDictionary *dic = nil;
    

    return dic;
}

/**
 @brief  获取所有的最近聊天数据
 @return 聊天数据
 */
- (NSMutableArray *)selectAllRecentData
{
    __block NSMutableArray *dataArr = [[NSMutableArray alloc] initWithCapacity:0];
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db)
     {
         if (![db tableExists:TABLE_RECENTCHAT]) {
             return;
         }
         NSString *sql = [NSString stringWithFormat:@"select * from %@ where order by %@ desc", TABLE_RECENTCHAT, RC_updateTime];
         
         FMResultSet *rs = [db executeQuery:sql];
         while([rs next])
         {
             RecentChat *recentChat = [RecentChat recentConcactDataFromDB:rs];
             [dataArr addObject:recentChat];
         }
         [rs close];
     }];
    
    return dataArr;
}

/**
 @brief  获取最近聊天表未读的消息数目
 @return 未读消息数
 */
- (int)selectTotalUnreadChatMsgCount
{
    __block int count = 0;
    
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        if (![db tableExists:TABLE_RECENTCHAT]) {
            return;
        }
        
        NSString *sql = [NSString stringWithFormat:@"select sum(%@) from %@",RC_unreadCount,TABLE_RECENTCHAT];
        FMResultSet *rs = [db executeQuery:sql];
        if ([rs next]) {
            count = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return count;
}


/**
 @brief  获取某个客户未读消息数
 @param  friendid  好友id
 @return 消息数
 */
- (int)selecteUnreadChatMsgCountWithFriendid:(NSString *)friendid {
    __block int count = 0;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select sum(%@) from %@ where %@ = %@",RC_unreadCount,TABLE_RECENTCHAT,RC_friendid,friendid];
        FMResultSet *rs = [db executeQuery:sql];
        if ([rs next]) {
            count = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return count;
}

/**
 @brief  根据好友ID重置未读的消息数目
 @param  friendid  好友id
 @return 修改是否成功
 */
- (BOOL)resetUnreadChatMsgCountWithFriendid:(NSString *)friendid {
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=? WHERE %@=?", TABLE_RECENTCHAT, RC_unreadCount,RC_friendid];
        NSArray *args = @[@(0), objectToString(friendid)];
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}

/**
 @brief  通过客户ID更新会话未读消息数
 @param  friendid  好友id
 @param  count 未读消息数
 @return 更新是否成功
 */
- (BOOL)updateUnreadChatMsgCountWithFriendid:(NSString *)friendid count:(NSInteger)count {
    BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString * sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=? WHERE %@=?", TABLE_RECENTCHAT, RC_unreadCount, RC_friendid];
    NSArray *args = [NSArray arrayWithObjects:@(count),friendid,nil];
    
    bol = [dbQueue.database executeUpdate:sql withArgumentsInArray:args];

    
    return bol;
}

/**
 @brief  队列中通过客户ID更新会话未读消息数
 @param  storeId  导购ID
 @param  count 未读消息数
 @return 更新是否成功
 */
- (BOOL)updateUnreadChatMsgCountWithFriendidAtQueue:(NSString *)storeId count:(NSInteger)count
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        bol = [self updateUnreadChatMsgCountWithFriendid:storeId count:count];
    }];
    
    return bol;
}



@end
